package com.jiepos.mpos.core.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiepos.mpos.common.constant.SystemConstant;

 

/**
 * 
 * <p>标题: —— ftp工具类，包含数据的上传下载等</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @author 娄伟峰
 * @version 1.0
 * @since 2017年9月11日 下午2:25:48
 * @history（历次修订内容、修订人、修订时间等）
 */
public class FtpUtil {
	
	private static final Logger log = LoggerFactory.getLogger(FtpUtil.class);
	
	private FtpUtil() {
		// null
	}
	
	/**
	 * 连接FTP 
	 * @param ftpClient ftp连接
	 * @param hostname ip
	 * @param port 断开
	 * @param username 用户名
	 * @param password 密码
	 * @return 是否连接
	 */
	public static  boolean connect(FTPClient ftpClient,String hostname, int port, String username, String password,String toEncoding){
		log.debug("开始连接ip为"+hostname+"的渠道");
			try {
				ftpClient.connect(hostname, port);
			} catch (SocketException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			ftpClient.setControlEncoding(toEncoding);
			if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				try {
					if (ftpClient.login(username, password)) {
						return true;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return false;
	}
	
	/**
	 * 断开FTP链接 
	 * @param ftpClient FTP通讯
	 */
	public static void disconnect(FTPClient ftpClient){
		if (ftpClient.isConnected()) {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * FTP下载文件
	 * @param remote 远程文件名称
	 * @param localPath 本地存放路径
	 * @param localName 下载后的本地文件名称
	 * @param bakSuffix 临时文件格式
	 * @param fileFormat 文件格式
	 * @return 下载结果
	 * @throws IOException 异常
	 */
	public static boolean download(FTPClient ftpClient,String remote,String localPath,String localName,String bakSuffix, String fileSuffix,String fromEncoding){
		boolean result = false;
		log.debug("开始下载文件"+remote);
		// 设置被动模式
		ftpClient.enterLocalPassiveMode();
		try {
			// 设置以二进制方式传输
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 检查远程文件是否存在
		FTPFile[] files = null;
		try {
			files = ftpClient.listFiles(new String(remote.getBytes(fromEncoding), SystemConstant.UTF_ENCODING));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (files.length != 1) {
			log.error("文件"+remote+"不存在！");
			return result;
		}
		
		File bakFile = FileUtils.makeFile(localPath+File.separator+localName+bakSuffix);
		if(bakFile == null){
			return result;
		}
		
		OutputStream out = null;
		InputStream in = null;
		byte[] bytes = new byte[1024];
		int c;
		boolean upNewStatus = false;
		try {
			out = new FileOutputStream(bakFile);
			in = ftpClient.retrieveFileStream(new String(remote.getBytes(fromEncoding), SystemConstant.UTF_ENCODING));
			while ((c = in.read(bytes)) != -1) {
				out.write(bytes, 0, c);
			}
			
			upNewStatus = ftpClient.completePendingCommand();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(null != in){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(null != out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		if (upNewStatus) {
			File file = new File(localPath+File.separator+localName+fileSuffix);
			result = bakFile.renameTo(file);
		}			
	
		return result;
	}
}
